package com.hhwy.components;

import com.hhwy.HslCommunication.ModBus.ModbusTcpNet;
import com.hhwy.domain.PressureCheck;
import com.hhwy.service.IPressureCheckService;
import com.hhwy.utils.SpringBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zhanglele
 * @since 2024/9/6
 */
@Component
public class ReadModbusSocket {

//    @Value("${pressure-socket.port}")
//    private Integer port;
//
//    @Value("${pressure-socket.enable}")
//    private boolean enable;

    private static final Logger log = LoggerFactory.getLogger(ReadModbusSocket.class);

    private static ServerSocket serverSocket = null;

    private static final ThreadPoolExecutor threadpool = new ThreadPoolExecutor(15, 15,
            10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

    private static final ConcurrentLinkedQueue<PressureCheck> dataList = new ConcurrentLinkedQueue<>();

    @Bean
    public void startModbusReadSocket() {
        if (true) {
            new Thread(() -> {
                try {
                    serverSocket = new ServerSocket(18234);
                    log.info("startModbusReadSocket started on port 18234");
                    while (true) {
                        Socket clientSocket = serverSocket.accept();
                        threadpool.execute(new ReadModbusSocket.ClientHandler(clientSocket));
                    }
                } catch (IOException e) {
                    log.error("Error starting startModbusReadSocket server", e);
                } finally {
                    stop();
                }
            }).start();

            // 启动入库线程
            new Thread(new ReadModbusSocket.DataSaver()).start();
        }
    }

    public void stop() {
        try {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        } catch (IOException e) {
            log.error("Error closing server socket", e);
        }
    }

    private static class ClientHandler implements Runnable {
        private final Socket clientSocket;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        @Override
        public void run() {
            try (BufferedInputStream in = new BufferedInputStream(clientSocket.getInputStream())) {
                int r;
                List<Integer> l = new LinkedList<>();
                while ((r = in.read()) != -1) {
                    l.add(r);
                    if (l.size() == 7) {

                        if(l.get(4)==1){
                            processPressureData(l);
                            log.info(String.valueOf(l));
                        }
                        l.clear();
                    }
                }

            } catch (IOException e) {
                log.error("Error handling client connection", e);
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    log.error("Error closing client socket", e);
                }
            }
        }

        private void processPressureData(List<Integer> data) {

        }
    }

    private static class DataSaver implements Runnable {
        @Override
        public void run() {
            while (true) {
//                try {
//                    if (dataList.size() > 60) {
//                        IPressureCheckService pressureCheckService = SpringBeanUtils.getApplicationContext().getBean(IPressureCheckService.class);
//                        pressureCheckService.saveBatch(new ArrayList<>(dataList));
//                        dataList.clear();
//                    }
//                } catch (Exception e) {
//                    log.error("Error saving pressure data", e);
//                }
//                try {
//                    Thread.sleep(5000); // 每5秒尝试一次
//                } catch (InterruptedException e) {
//                    Thread.currentThread().interrupt();
//                    log.error("DataSaver thread interrupted", e);
//                }
            }
        }
    }
}
